package com.atguigu.r_thread_talk;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/*需求
* a打印5次
* b打印10次
* c打印15次
* 如此打印十五次*/
class Printer{
    String flag = "a";
    ReentrantLock lock = new ReentrantLock();
    Condition condition1 = lock.newCondition();
    Condition condition2 = lock.newCondition();
    Condition condition3 = lock.newCondition();
    // 打印5次
    public void print5() throws InterruptedException {
        lock.lock();
        try{
            while (flag!="a"){
                condition1.await();
            }
            for (int i = 1; i <= 5; i++) {
                System.out.println(Thread.currentThread().getName()+"..."+i);
            }
            flag="b";
            condition2.signal();
        }finally {
            lock.unlock();
        }
    }
    // 打印10次
    public void print10() throws InterruptedException {
        lock.lock();
        try{
            while (flag!="b"){
                condition2.await();
            }
            for (int i = 1; i <= 10; i++) {
                System.out.println(Thread.currentThread().getName()+"..."+i);
            }
            flag="c";
            condition3.signal();
        }finally {
            lock.unlock();
        }
    }
    // 打印15次
    public void print15() throws InterruptedException {
        lock.lock();
        try{
            while (flag!="c"){
                condition3.await();
            }
            for (int i = 1; i <= 15; i++) {
                System.out.println(Thread.currentThread().getName()+"..."+i);
            }
            flag="a";
            condition1.signal();
        }finally {
            lock.unlock();
        }
    }
}

public class Test {
    public static void main(String[] args) {
        Printer printer = new Printer();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    printer.print5();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "a").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    printer.print10();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "b").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    printer.print15();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "c").start();
    }
}
